package de.justphil.tcg.tcgserver.game.mechanics.util.tools;

import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;

import org.slf4j.Logger;
import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;


public abstract class IterationHelper<T> {

	private static final Logger log = gameLogger(IterationHelper.class);

	private Collection<T> list;

	public IterationHelper(Collection<T> list) {

		this.list = list;
	}

	protected abstract void execute(T listElement);

	/**
	 * The execute Method will be executed for each list element. This will work
	 * even if the list is manipulated while iterating through it.
	 */
	public void safeExecuteForAll() {

		Collection<T> finishedElements = new ArrayList<T>();

		while (true) {
			try {

				for (T element : list) {

					if (!finishedElements.contains(element)) {

						execute(element);
						finishedElements.add(element);
					}
				}
				break;

			} catch (ConcurrentModificationException e) {

				log.debug(
						"Save Execution has been interrupted through concurrent modification but will be resumed!.",
						new Object[] {});
			}
		}
	}

}
